import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/users.vue'
import Rights from '../components/power/rights.vue'
import Roles from '../components/power/roles.vue'
import GoodsList from '../components/goods/list.vue'
import Add from '../components/goods/add.vue'
import Update from '../components/goods/update.vue'
import CategoryList from '../components/category/list.vue'
import AddCategory from '../components/category/add.vue'
import UpdateCategory from '../components/category/update.vue'
import CouponList from '../components/coupon/list.vue'
import AddCoupon from '../components/coupon/add.vue'
import UpdateCoupon from '../components/coupon/update.vue'
import orderList from '../components/order/list.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    // home页面添加子页面Welcome，再重定向到Welcome
    {
      path: '/home',
      component: Home,
      redirect: '/Welcome',
      children: [
        { path: '/Welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rigths', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/goods', component: GoodsList },
        { path: '/goods/add', component: Add },
        { path: '/goods/update', component: Update },
        { path: '/category', component: CategoryList },
        { path: '/category/add', component: AddCategory },
        { path: '/category/update', component: UpdateCategory },
        { path: '/coupon', component: CouponList },
        { path: '/coupon/add', component: AddCoupon },
        { path: '/coupon/update', component: UpdateCoupon },
        { path: '/order', component: orderList }
      ]
    }
  ]
})

// 在（export default router）暴露路由之前挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to代表将要访问的路径 ，from代表从那个路径跳转而来，next是个函数，表示放行 1.next()放行 2.next('/login')强至跳转
  // '/login'无权限页面直接放行
  if (to.path === '/login') return next()
  // 对于有权限的页面，先判断是否有token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
